#include "RR.h"
#include <stdio.h>
#include <stdlib.h>

int check_finish (int run_time[], int num)
{
	for (int i = 0; i < num; i++)
	{
		if (run_time[i] != 0)
			return 0;
	}
	return 1;
}

/**
 * 函数: calculateTimes
 * 功能: 根据时间片轮转调度算法计算每个进程的完成时间、周转时间和等待时间
 *
 * 参数:
 *  - processes: 指向包含多个进程信息的数组
 *  - n: 进程数量
 *  - time_slice: 时间片长度
 *
 * 描述:
 *  计算进程的完成时间，周转时间和等待时间并存在结构体中即可
 */
	void
calculateTimes (Process *processes, int n, int time_slice)
{
	// TODO
	//   int queue[n];
	//   int que_pos = 0;

	for (int i = 0; i < n; i++)
	{
		processes[i].remaining_time = processes[i].burst_time;

		processes[i].completion_time = 0;
		processes[i].turnaround_time = 0;
		processes[i].waiting_time = 0;
	}

	int now_time = 0;

	// start every process
	while (1)
	{
		int zero_count = 0;

		for (int i = 0; i < n; i++)
		{
			int remain_time = processes[i].remaining_time;

			if (remain_time > 0 && processes[i].arrival_time <= now_time)
			{
				int min_time
					= remain_time < time_slice ? remain_time : time_slice;

				remain_time -= min_time;
				now_time += min_time;

				if (remain_time == 0)
				{
					processes[i].completion_time = now_time;
				}
			}

			if (remain_time == 0)
				zero_count++;

			processes[i].remaining_time = remain_time;
		}

		if (zero_count == n)
		{
			break;
		}
	}

	for (int i = 0; i < n; i++)
	{
		processes[i].turnaround_time
			= processes[i].completion_time - processes[i].arrival_time;
		processes[i].waiting_time
			= processes[i].turnaround_time - processes[i].burst_time;
	}
}
